package server

import (
	"9-13yk/common/model/mysql"
	"9-13yk/common/model/redis"
	"9-13yk/common/pkg"
	"9-13yk/common/proto/user"
	"context"
	"errors"
	"fmt"
	"github.com/google/uuid"
	"gorm.io/gorm"
	"strconv"
	"time"
)

func ProductList(req *user.ProductListReq) (*user.ProductListResp, error) {
	list, err := mysql.MealProductsList(int(req.MealProductsTypes))
	if err != nil {
		return nil, errors.New("查询失败")
	}
	var lists []*user.List
	for _, products := range list {
		lists = append(lists, &user.List{
			MealProductsName:      products.MealProductsName,
			MealProductsPrice:     float32(products.MealProductsPrice),
			MealProductsScore:     float32(products.MealProductsScore),
			MealProductsInter:     products.MealProductsInter,
			MealProductsInventory: int64(products.MealProductsInventory),
			MealProductsImage:     products.MealProductsImage,
			MealProductsType:      int64(products.MealProductsType),
			MealProductsTypes:     int64(products.MealProductsTypes),
		})
	}
	sprintf := fmt.Sprintf("list:%d", req.MealProductsTypes)
	redis.Rdb.Set(context.Background(), sprintf, lists, time.Minute*30)
	return &user.ProductListResp{Lists: lists}, nil
}

func SettlementAdd(req *user.SettlementAddReq) (*user.SettlementAddResp, error) {
	show, err := mysql.MealProductShow(int(req.MealProductsId))
	if err != nil {
		return nil, errors.New("餐品查询失败")
	}
	if show.MealProductsInventory <= 0 {
		return nil, errors.New("库存不足")
	}
	settlement := mysql.Settlement{
		Model:             gorm.Model{},
		UserId:            int(req.UserId),
		MealProductsId:    int(req.MealProductsId),
		MealProductsName:  show.MealProductsName,
		MealProductsPrice: show.MealProductsPrice,
		MealProductsScore: show.MealProductsScore,
		MealProductsInter: show.MealProductsInter,
		MealProductsImage: show.MealProductsImage,
		MealProductsNotes: req.MealProductsNotes,
	}
	err = mysql.SettlementCreate(&settlement)
	if err != nil {
		return nil, errors.New("添加失败")
	}

	return &user.SettlementAddResp{Greet: "添加成功"}, nil
}

func OrderAdd(req *user.OrderAddReq) (*user.OrderAddResp, error) {
	show, err := mysql.MealProductShow(int(req.MealProductsId))
	if err != nil {
		return nil, errors.New("餐品查询失败")
	}
	_, err = mysql.UserShow(int(req.UserId))
	if err != nil {
		return nil, errors.New("用户查询失败")
	}
	con, err := mysql.CouponShow(int(req.CouponId))
	if err != nil {
		return nil, errors.New("优惠券查询失败")
	}
	settlementShow, err := mysql.SettlementShow(req.Settlement)
	if err != nil {
		return nil, errors.New("点餐查询失败")
	}
	newString := uuid.NewString()
	order := mysql.Order{
		Model:          gorm.Model{},
		UserId:         int(req.UserId),
		MealProductsId: int(req.MealProductsId),
		CouponId:       int(req.CouponId),
		OrderSn:        newString,
		OrderStatus:    1,
		PayType:        int(req.PayType),
	}
	err = mysql.OrderAdd(&order)
	if err != nil {
		return nil, errors.New("添加失败")
	}
	inventory := show.MealProductsInventory - 1
	m := map[string]string{
		"meal_products_inventory": strconv.Itoa(inventory),
	}
	err = mysql.InventoryUpdate(m)
	/*	if err != nil {
		return nil, errors.New("库存扣减失败")
	}*/
	f := settlementShow.Price
	if settlementShow.Price >= con.CouponFullPrice {
		f = settlementShow.Price - con.CouponDisCountPrice
	} else {
		f = settlementShow.Price
	}
	float := strconv.FormatFloat(f, 'f', 2, 64)

	alipays := pkg.Alipays()
	pay := alipays.ALiPay(settlementShow.TableNum, newString, float)
	return &user.OrderAddResp{
		OrderSn: newString,
		Url:     pay,
	}, nil
}

func PayCall(req *user.PayCallReq) (*user.PayCallResp, error) {
	fmt.Println("支付回调")
	var status int
	if req.Status == "WAIT_BUYER_PAY" {
		status = 1
	} else if req.Status == "TRADE_CLOSED" {
		status = 2
	} else if req.Status == "TRADE_SUCCESS" {
		status = 3
	} else if req.Status == "TRADE_FINISHED" {
		status = 4
	}
	var order *mysql.Order
	err := mysql.DB.Debug().Model(&order).Where("order_sn = ?", req.OrderSn).Updates(status).Error
	if err != nil {
		return nil, errors.New("修改失败")
	}
	return &user.PayCallResp{
		Success: "支付宝回调失败",
	}, nil
}

func GetOrderList(req *user.GetOrderListReq) (*user.GetOrderListResp, error) {
	list, err := mysql.GetOrderList()
	if err != nil {
		return nil, errors.New("查询失败")
	}
	var lists []*user.OrderList
	for _, order := range list {
		lists = append(lists, &user.OrderList{
			UserId:         int64(order.UserId),
			MealProductsId: int64(order.MealProductsId),
			CouponId:       int64(order.CouponId),
			SettlementId:   int64(order.SettlementId),
			OrderSn:        order.OrderSn,
			OrderStatus:    int64(order.OrderStatus),
			PayType:        int64(order.PayType),
		})
	}
	return &user.GetOrderListResp{Lists: lists}, nil
}

func CouPonList(req *user.CouponListReq) (*user.CouponListResp, error) {
	list, err := mysql.GetCouponList()
	if err != nil {
		return nil, errors.New("查询失败")
	}
	var lists []*user.CouPonList
	for _, coupons := range list {
		lists = append(lists, &user.CouPonList{
			CouponStatus:        int64(coupons.CouponStatus),
			CouponFullPrice:     float32(coupons.CouponFullPrice),
			CouponDisCountPrice: float32(coupons.CouponDisCountPrice),
			CouponType:          int64(coupons.CouponType),
			CouponsSn:           coupons.CouponsSn,
		})
	}
	return &user.CouponListResp{Lists: lists}, nil
}

func CouPonAdd(req *user.CouponAddReq) (*user.CouponAddResp, error) {
	show, err := mysql.CouponsShow(int(req.CouPonsId))
	if err != nil {
		return nil, err
	}
	coupon := mysql.Coupon{
		Model:               gorm.Model{},
		UserId:              int(req.UserId),
		CouponStatus:        show.CouponStatus,
		CouponFullPrice:     show.CouponFullPrice,
		CouponDisCountPrice: show.CouponDisCountPrice,
		CouponType:          show.CouponType,
	}
	if show.CouponType == 1 {
		return nil, errors.New("优惠券已领取，不可重复领取")
	} else if show.CouponType == 2 {
		err := mysql.CouPonCreate(&coupon)
		if err != nil {
			return nil, errors.New("优惠券领取失败")
		}
	}
	return &user.CouponAddResp{Success: "优惠券领取成功"}, nil
}

func MyCouPonList(req *user.MyCouponListReq) (*user.MyCouponListResp, error) {
	list, err := mysql.GetCouponsList()
	if err != nil {
		return nil, errors.New("查询失败")
	}
	var lists []*user.MyCouPonList
	for _, coupon := range list {
		lists = append(lists, &user.MyCouPonList{
			UserId:              int64(coupon.UserId),
			CouponStatus:        int64(coupon.CouponStatus),
			CouponFullPrice:     float32(coupon.CouponFullPrice),
			CouponDisCountPrice: float32(coupon.CouponDisCountPrice),
			CouponType:          int64(coupon.CouponType),
		})
	}
	return &user.MyCouponListResp{
		Lists: lists,
	}, nil
}
